<template>
  <div class="container">
    <div class="app-container">
      <!-- 左面结构 -->
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin: 10px"
          type="text"
          size="small"
          placeholder="输入员工名称搜索"
          prefix-icon="el-icon-search"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          @node-click="selectNode"
        />
      </div>
      <!-- 右面结构 -->
      <div class="right">
        <!--        v-permission="add=employee"    -->
        <el-row class="operate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" label="头像" align="center" width="80">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <!--                             头像显示设置  .charAt(第几个字符) -->
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{row}">
              <span>{{ row.formOfEmployment===1 ?'正式' : row.formOfEmployment===2?'非正式' : row.formOfEmployment }} </span>
            <!-- <span v-if="row.formOfEmployment === 1">正式</span>
            <span v-else-if="row.formOfEmployment === 2">非正式</span>
            <span v-else>无</span> -->
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button
                  slot="reference"
                  style="margin-left: 10px"
                  size="mini"
                  type="text"
                >删除</el-button>
              </el-popconfirm>
            </template>

          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            layout="total, prev, pager, next"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>

    <!--   Excel 弹出 框 -->
    <!-- .sync语法糖帮我们自动写了 @update:showExcelDialog="showExcelDialog=$event" -->
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!--   分配角色 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="conter">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="btnRoleOk">确认</el-button>
          <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getDepartment } from '@/api/department' // getDepartment   //  组织架构
import { getEmployeeList, exportEmployee, delEmployee, getEmployeeDetail, getEnableRoleList, assignRole } from '@/api/employee'
import { transListToTreeData } from '@/utils/index'
import FileSaver from 'file-saver'
import ImportExcel from './import-excel'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      showExcelDialog: false, // /
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10, //  一页显示 多少条
        keyword: '' //  模糊字段搜素an
      },
      total: 0, // /  记录员工总数
      list: [],
      timer: null, // 定时器
      showRoleDialog: false, // 角色弹出框控制变量
      roleIds: [], //  用来双向绑定数据的
      roleList: [], //  接收角色列表
      currentUserId: null // 记录当前点击的用户id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const result = await getDepartment()
      this.depts = transListToTreeData(result, 0)
      this.queryParams.departmentId = this.depts[0].id // 头像设置  this.depts[第几项].id
      //  设置  选中的节点
      // 为什么使用$nextTick，因为我们设置完树形之后立刻选中首个节点，此时更新还没有完成，必须等待更新完成后，再去选中首个节点，所以需要使用$nextTick
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    //  获取员工列表
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    //  点击 树节点方法
    selectNode(node) {
      // console.log(node)
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 //  设置 第一页
      this.getEmployeeList()
    },
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值 新页码
      this.getEmployeeList() //  重新渲染
    },
    //  模糊 搜索
    changeValue() {
      // console.log(this.queryParams.keyword)
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // console.log('我执行了')
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    //  excel导出
    async exportEmployee() {
      const res = await exportEmployee()
      // console.log(res)
      FileSaver.saveAs(res, '员工信息表')
    },
    //  删除 员工
    async confirmDel(id) {
      // console.log(id)
      await delEmployee(id)
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
      this.$message.success('删除成功')
    },
    // 点击角色按钮弹出层
    async btnRole(id) {
      this.currentUserId = id
      this.roleList = await getEnableRoleList()
      const { roleIds } = await getEmployeeDetail(id)
      // console.log(roleIds)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async btnRoleOk() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style scoped>
.app-container{
  background: #fff;
  display: flex;
}
.left{
  width: 280px;
  padding: 20px;
  border-right: 1px solid #eaeef4;
}
.right{
flex: 1;
padding: 20px;
}
.operate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
</style>
